package eerbaar.action.internal.lib;

import java.util.Map;

import eerbaar.area.IArea;
import eerbaar.context.IContext;
import eerbaar.context.IParams;
import eerbaar.game.IGame;
import eerbaar.persona.IPersona;
import eerbaar.persona.PersonaFactory;
import eerbaar.position.IPosition;

public class AddPersonaAction extends AbstractAction {

    private static final String[] paramNames = new String[] { //
    "name", "count", "program", "position" // values
    };

    private int count;
    private String name;
    private IParams params;
    private String program;
    private String position;

    public AddPersonaAction(IParams params) {
        super("addPersona");
        this.params = params;

        setup(params);
    }

    @Override
    public void execute(IContext model) {

        IGame game = (IGame) model;
        IArea area = game.getArea();

        for (int i = 0; i < this.count; i++) {

            IPosition p = Global.calcPosition(game, area, this.position);
            if (p == null) {
                break;
            }

            IPersona e = PersonaFactory.create(this.name, p.getX(), p.getY());
            if (this.program != null) {
                e.setProgram(this.program);
            }

            area.addElement(e);
        }
    }

    @Override
    public void execute(IContext model, Map<String, String> map) {
        execute(model);
    }

    @Override
    public String[] getParamNames() {

        return paramNames;
    }

    @Override
    public IParams getParams() {

        return this.params;
    }

    @Override
    public void setParams(IParams params) {
        this.params = params;
        setup(params);
    }

    private void setup(IParams params) {

        this.name = params.get("name");
        this.position = params.get("position");
        this.count = Integer.parseInt(params.get("count"));

        if (params.get("program") != null) {
            this.program = params.get("program");
        }
    }
}
